package club.kunlingou.dsc.sqlclient.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;

import club.kunlingou.dsc.sqlclient.SqlClientConst;
import club.kunlingou.dsc.sqlclient.service.SqlClientService;

import static club.kunlingou.dsc.sqlclient.SqlClientConst.*;

@Service
public class SqlClientServiceImpl implements SqlClientService{
	
	@Autowired
	DataSource dataSource;
	
	@Autowired
	JdbcTemplate template;
	
	public String getType(String sql){
		if(StringUtils.isEmpty(sql)) {
			return null;
		}
		String type = sql.trim().toUpperCase().split(" ")[0];
		switch(type){
		case TYPE_INSERT:
			return TYPE_INSERT;
		case TYPE_DELETE:
			return TYPE_DELETE;
		case TYPE_UPDATE:
			return TYPE_UPDATE;
		case TYPE_SELECT:
			return TYPE_SELECT;
		case TYPE_CREATE:
			return TYPE_CREATE;
		}
		return null;
	}
	
	public JSONObject getResult(String sql) throws SQLException{
		JSONObject result = new JSONObject();
		String type = getType(sql);
		result.put("type", type);
		long t1;
		long t2;
		List<Map<String, Object>> list;
		switch(type) {
		case TYPE_SELECT:
			t1 = System.nanoTime();
			list = template.queryForList(sql);
			t2 = System.nanoTime();
			result.put("spendTime", (t2-t1)/1000000+"ms");
			result.put("data", list);
			result.put("cols", list.size());
			if(list.size()>0) {
				result.put("rows", list.get(0).size());
			}
			break;
		case TYPE_INSERT:
		case TYPE_UPDATE:
		case TYPE_DELETE:
		case TYPE_CREATE:
			t1 = System.nanoTime();
			list = new ArrayList<Map<String,Object>>();
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("resut", "SUCCESS");
			list.add(map);
			try {
				template.execute(sql);
			}catch (Exception e) {
				e.printStackTrace();
				map.put("resut", "FAIL");
			}
			t2 = System.nanoTime();
			result.put("spendTime", (t2-t1)/1000000+"ms");
			result.put("data", list);
			result.put("cols", 1);
			result.put("rows", 1);
			break;
		}
		return result;
	}
	
}
